from rest_framework import filters, settings
from django.db.models.constants import LOOKUP_SEP
from mongoengine import Q
from functools import reduce
import operator

class MongoSearchFilter(filters.BaseFilterBackend):
    """
    Filter that only allows users to see their own objects.
    """
    search_param = "search"# search

    def filter_queryset(self, request, queryset, view):
        # 被list调用 self.filter_queryset(self.get_queryset())
        search_fields = getattr(view, 'mongo_search_fields', None) # [name, label]
        search_term = request.query_params.get(self.search_param, '') # ?search=xxx
        if not search_fields or not search_term:
            return queryset
        print('^!@' * 30)
        orm_lookups = [
            "{}{}{}".format(str(search_field), LOOKUP_SEP, 'icontains')
            for search_field in search_fields
        ] # ['name__icontains', 'label__icontains']

        queries = [
            Q(**{orm_lookup: search_term}) # Q对象
            for orm_lookup in orm_lookups
        ] # [Q(name__icontains=xxx), Q(label__icontains=xxx)]
        # Q(name__icontains=xxx) | Q(label__icontains=xxx)

        queryset = queryset.filter(reduce(operator.or_, queries))
        return queryset